<template>
  <BasicModal
    v-bind="$attrs"
    :showFooter="true"
    @register="registerModal"
    @ok="handleSubmit"
    width="70%"
    :okText="okText"
  >
    <template #title>
      <Icon icon="ant-design:apartment-outlined" class="pr-1 m-1" />
      <span>管理设备 - {{ groupName }}</span>
    </template>
    <div class="manage-devices-content">
      <div class="mb-3">
        <a-input
          v-model:value="searchText"
          placeholder="搜索设备名称"
          allow-clear
          @change="handleSearch"
          style="width: 300px"
        >
          <template #suffix>
            <Icon icon="ant-design:search-outlined" />
          </template>
        </a-input>
      </div>
      <BasicTable @register="registerTable">
        <template #firstColumn="{ record }">
          <div :title="record.name">
            {{ record.name }}
          </div>
        </template>
        <template #active="{ record }">
          <Tag v-if="record.active == true" color="success">在线</Tag>
          <Tag v-if="record.active == false" color="error">离线</Tag>
        </template>
      </BasicTable>
    </div>
  </BasicModal>
</template>
<script lang="ts" setup name="ViewsTbGroupManageDevices">
  import { ref, computed } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Icon } from '/@/components/Icon';
  import { Tag } from 'ant-design-vue';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { getTenantDeviceInfoList } from '/@/api/tb/device';
  import { addDeviceToGroup } from '/@/api/tb/group';

  const emit = defineEmits(['success', 'register']);

  const { showMessage } = useMessage();
  const groupRecord = ref<any>({});
  const searchText = ref('');
  const selectedRowKeys = ref<string[]>([]);

  const groupName = computed(() => groupRecord.value.name || '');
  const okText = computed(() => `确定 (已选${selectedRowKeys.value.length}个设备)`);

  const tableColumns: BasicColumn[] = [
    {
      title: '设备名称',
      dataIndex: 'name',
      key: 'name',
      align: 'left',
      slot: 'firstColumn',
      ellipsis: false,
    },
    {
      title: '产品',
      dataIndex: 'deviceProfileName',
      key: 'deviceProfileName',
      align: 'left',
      ellipsis: false,
    },
    {
      title: '标签',
      dataIndex: 'label',
      key: 'label',
      align: 'left',
      ellipsis: false,
    },
    {
      title: '状态',
      align: 'center',
      width: 100,
      slot: 'active',
    },
    {
      title: '创建时间',
      dataIndex: 'createdTime',
      key: 'createdTime',
      format: 'date|YYYY-MM-DD HH:mm:ss',
      width: 160,
      align: 'center',
    },
  ];

  const [registerTable, { reload, getSelectRowKeys }] = useTable({
    rowKey: (record) => record.id.id,
    api: getTenantDeviceInfoList,
    beforeFetch: wrapFetchParams,
    columns: tableColumns,
    showTableSetting: false,
    useSearchForm: false,
    canResize: true,
    pagination: {
      pageSize: 10,
    },
    rowSelection: {
      type: 'checkbox',
      onChange: (keys: string[]) => {
        selectedRowKeys.value = keys;
      },
    },
  });

  function wrapFetchParams(param: any) {
    const entityGroupId = groupRecord.value?.id?.id;
    return {
      ...param,
      textSearch: searchText.value,
      inGroup: false, // 过滤已有分组的设备
      ...(entityGroupId ? { entityGroupId } : {}), // 带上当前设备组ID，后端才能过滤
    };
  }

  function handleSearch() {
    reload();
  }

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ loading: true });
    groupRecord.value = { ...data };
    searchText.value = '';
    selectedRowKeys.value = [];

    // 如果有已选设备，设置选中状态
    // TODO: 这里后续可以从接口获取该设备组已关联的设备ID列表

    await reload();
    setModalProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      setModalProps({ confirmLoading: true });

      const selectedKeys = getSelectRowKeys();

      if (selectedKeys.length === 0) {
        showMessage('请至少选择一个设备', 'warning');
        return;
      }

      // 调用 API 保存设备到分组
      await addDeviceToGroup({
        deviceGroupId: groupRecord.value.id.id,
        deviceIds: selectedKeys,
      });

      showMessage(`成功为设备组添加 ${selectedKeys.length} 个设备！`);
      setTimeout(closeModal);
      emit('success', { groupId: groupRecord.value.id, deviceIds: selectedKeys });
    } catch (error: any) {
      showMessage(`添加设备失败: ${error.message || '未知错误'}`, 'error');
      console.log('error', error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
<style lang="less" scoped>
  .manage-devices-content {
    padding: 0;
  }
</style>
